package com.tj.bo.trade.server.service.rule;

import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.tj.bo.common.conf.util.CalculatorUtils;
import com.tj.bo.trade.client.enums.OrderStatusEnum;
import com.tj.bo.trade.client.enums.TradeTypeEnum;
import com.tj.bo.trade.server.entity.BinaryTradeEntity;
import com.tj.bo.trade.server.entity.bussiness.TradeDailyAvgEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 青铜 前1天交易金额离散系数大于0.5
 * Author: Amarendar
 * Date: 2020/8/25 上午11:01
 */
@Service
public class TradeBronzeRule3 extends BaseTradeRule {

    private static final String RULE_NAME = "前1天交易金额离散系数大于0.5";

    private static final Integer DEFAULT_PRIORITY = 3;

    @Override
    public void checkRouterRule(RouterContext routerContext, List<RuleResultVO> ruleResultVOList) {
        Date endDate = DateUtil.getPatternDate(new Date(), "yyyy-MM-dd");
        Date startDate = DateUtil.addDate(endDate, -1);

        List<BinaryTradeEntity> binaryTradeEntityList = binaryTradeDao.selectsBinaryTradeListByTime(routerContext.getUserCode(), routerContext.getProductCode(), OrderStatusEnum.CLOSING.getCode(), TradeTypeEnum.REAL_TRADE.getCode(), startDate, endDate);
        if (CollectionUtils.isEmpty(binaryTradeEntityList) || binaryTradeEntityList.size() < redisConfigUtil.getChangeOddsUserTradeNumbers()) {
            ruleResultVOList.add(new RuleResultVO(routerContext.getProductCode(), RULE_NAME).setMessage("订单数过少"));
            return;
        }

        int orderNum = binaryTradeEntityList.size();

        Integer[] amounts = binaryTradeEntityList.stream().map(e -> e.getAmount().intValue()).toArray(Integer[]::new);

        //离散系数
        double coefficient = CalculatorUtils.getDispersionCoefficient(orderNum, amounts);
        if (coefficient > 0.5) {
            RuleResultVO ruleResultVO = new RuleResultVO(routerContext.getProductCode(), RULE_NAME);
            ruleResultVO.setPriority(DEFAULT_PRIORITY);
            ruleResultVO.setMode(0);
            ruleResultVO.setChangeValue(BigDecimal.valueOf(-0.05));
            ruleResultVO.setMessage("前1天交易金额离散系数大于0.5");
            ruleResultVOList.add(ruleResultVO);
        } else {
            ruleResultVOList.add(new RuleResultVO(routerContext.getProductCode(), RULE_NAME).setMessage("前1天交易金额离散系数大于0.5-条件不满足"));
        }

    }
}
